<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import { ChatAPI } from "@/api/knowledge";
import type { Message, ChatSession } from "@/api/knowledge";
import { ElMessage } from "element-plus";

// 用户ID（实际项目中应该从用户系统获取）
const userId = ref("test_user");

// 会话相关
const sessionList = ref<ChatSession[]>([]);
const currentSession = ref<ChatSession>();
const messageList = ref<Message[]>([]);

// 输入相关
const question = ref("");
const loading = ref(false);
const streamingResponse = ref("");

// 获取会话列表
const getSessionList = async () => {
  try {
    const response = await ChatAPI.getSessions(userId.value);
    // 将返回的数据格式转换为内部会话格式
    sessionList.value = response.map((session) => ({
      id: session.sessionId,
      title: session.sessionName?.trim() || "新会话",
      updateTime: session.sessionTime,
    }));
    // 如果有当前会话ID则保持选中，否则选中第一个会话
    if (!currentSession.value?.id && sessionList.value.length > 0) {
      currentSession.value = sessionList.value[0];
      await getMessageList();
    }
  } catch (error) {
    ElMessage.error("获取会话列表失败");
  }
};

// 获取消息列表
const getMessageList = async () => {
  if (!currentSession.value) return;
  try {
    const response = await ChatAPI.getMessages(currentSession.value.id);
    // 将接收到的消息格式转换为内部消息格式
    messageList.value = response.map((msg) => ({
      id: msg.id || Date.now().toString(),
      content: msg.text,
      role: msg.messageType === "USER" ? "user" : "assistant",
      createTime: new Date().toISOString(),
    }));
    // 触发响应式更新
    messageList.value = [...messageList.value];
    // 消息加载完成后，自动滚动到底部
    await nextTick(() => {
      const chatBox = document.querySelector(".chat-content");
      if (chatBox) {
        chatBox.scrollTop = chatBox.scrollHeight;
        chatBox.scrollTo({
          top: chatBox.scrollHeight,
          behavior: "smooth",
        });
      }
    });
  } catch (error) {
    ElMessage.error("获取消息记录失败");
  }
};

// 新建会话
const createNewSession = () => {
  currentSession.value = undefined;
  messageList.value = [];
  question.value = "";
};

// 切换会话
const handleSessionChange = async (session: ChatSession) => {
  currentSession.value = session;
  await getMessageList();
};

// 滚动到底部的公共方法
const scrollToBottom = () => {
  nextTick(() => {
    const chatBox = document.querySelector(".chat-content");
    if (chatBox) {
      chatBox.scrollTop = chatBox.scrollHeight;
      chatBox.scrollTo({
        top: chatBox.scrollHeight,
        behavior: "smooth",
      });
    }
  });
};

// 发送消息
const handleSend = async () => {
  console.log("发送消息时的问题内容:", question.value);
  if (!question.value) {
    ElMessage.warning("请输入问题内容");
    return;
  }

  loading.value = true;
  streamingResponse.value = "";
  let eventSource: EventSource | null = null;

  try {
    // 立即显示用户消息
    const userMessage = {
      id: Date.now().toString(),
      content: question.value,
      role: "user",
      createTime: new Date().toISOString(),
    };
    messageList.value.push(userMessage);

    // 添加AI等待状态
    const aiMessage = {
      id: (Date.now() + 1).toString(),
      content: "思考中...",
      role: "assistant",
      createTime: new Date().toISOString(),
    };
    messageList.value.push(aiMessage);
    messageList.value = [...messageList.value];
    scrollToBottom();

    // 使用ChatAPI发送消息
    let fullResponse = "";
    eventSource = new EventSource(
      `${import.meta.env.VITE_APP_BASE_API}/wz/api/chat/ai/generateStream?message=${encodeURIComponent(question.value)}&sessionId=${currentSession.value?.id ? encodeURIComponent(currentSession.value.id) : ""}&userId=${encodeURIComponent(userId.value)}`
    );

    eventSource.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        if (data.result?.metadata?.finishReason === "stop") {
          if (data.result?.output?.text) {
            fullResponse += data.result.output.text;
            aiMessage.content = fullResponse;
            messageList.value = [...messageList.value];
            scrollToBottom();
          }
          eventSource?.close();
          eventSource = null;
          loading.value = false;
          // 保存当前会话ID
          const currentSessionId = currentSession.value?.id;
          // 刷新会话列表
          getSessionList();
          // 如果之前有选中的会话，恢复选中状态
          if (currentSessionId) {
            getMessageList();
          }
          return;
        }

        if (data.result?.output?.text) {
          fullResponse += data.result.output.text;
          aiMessage.content = fullResponse;
          messageList.value = [...messageList.value];
          scrollToBottom();
        }
      } catch (e) {
        console.error("解析消息失败:", e);
        eventSource?.close();
        eventSource = null;
        loading.value = false;
        ElMessage.error("消息解析失败");
      }
    };

    eventSource.onerror = () => {
      eventSource?.close();
      eventSource = null;
      loading.value = false;
      ElMessage.error("消息发送失败");
    };

    question.value = "";
  } catch (error) {
    console.error("发送消息失败:", error);
    eventSource?.close();
    eventSource = null;
    ElMessage.error("发送消息失败");
  } finally {
    loading.value = false;
  }
};

// 清空当前会话
const handleClear = () => {
  messageList.value = [];
  question.value = "";
};

// 初始化
onMounted(() => {
  getSessionList();
});
</script>

<template>
  <div class="app-container">
    <div class="chat-container">
      <!-- 会话列表 -->
      <div class="session-list">
        <div class="session-header">
          <h3>会话列表</h3>
          <el-button type="primary" size="small" @click="createNewSession">
            新建会话
          </el-button>
        </div>
        <el-scrollbar>
          <div
            v-for="session in sessionList"
            :key="session.id"
            class="session-item"
            :class="{ active: currentSession?.id === session.id }"
            @click="handleSessionChange(session)"
          >
            <span class="session-title">{{ session.title }}</span>
            <span class="session-time">{{ session.updateTime }}</span>
          </div>
        </el-scrollbar>
      </div>

      <!-- 聊天区域 -->
      <div class="chat-main">
        <!-- 消息列表 -->
        <div class="chat-box">
          <el-scrollbar>
            <div v-if="messageList.length === 0" class="empty-tip">
              {{ currentSession ? "暂无消息" : "请选择或创建一个会话" }}
            </div>
            <div v-else class="chat-content">
              <div
                v-for="message in messageList"
                :key="message.id"
                class="chat-item"
                :class="message.role === 'user' ? 'question' : 'answer'"
              >
                <div class="chat-avatar">
                  <el-avatar
                    :icon="message.role === 'user' ? 'UserFilled' : 'ChatRound'"
                  />
                </div>
                <div class="chat-text">{{ message.content }}</div>
              </div>
            </div>
          </el-scrollbar>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input">
          <el-input
            v-model="question"
            type="textarea"
            :rows="3"
            placeholder="请输入您的问题"
            :disabled="loading"
            @keyup.enter="handleSend"
          />
          <div class="chat-actions">
            <el-button @click="handleClear" :disabled="loading">清空</el-button>
            <el-button
              type="primary"
              @click="handleSend"
              :loading="loading"
              :disabled="false"
            >
              发送
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.chat-container {
  display: flex;
  height: calc(100vh - 130px);
  background-color: #fff;
  border-radius: 4px;
}

.session-list {
  display: flex;
  flex-direction: column;
  width: 250px;
  border-right: 1px solid #e4e7ed;
}

.session-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;

  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
  }
}

.session-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
  padding: 15px 20px;
  cursor: pointer;
  border-bottom: 1px solid #f0f2f5;
  transition: background-color 0.3s;

  &:hover {
    background-color: #f5f7fa;
  }

  &.active {
    background-color: #ecf5ff;
  }
}

.session-title {
  font-size: 14px;
  color: #333;
}

.session-time {
  font-size: 12px;
  color: #999;
}

.chat-main {
  display: flex;
  flex: 1;
  flex-direction: column;
  padding: 20px;
}

.chat-box {
  flex: 1;
  padding: 20px;
  margin-bottom: 20px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.chat-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.chat-item {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  max-width: 70%;
  margin: 16px 0;

  &.question {
    flex-direction: row-reverse;
    align-self: flex-end;

    .chat-text {
      margin-right: 8px;
      color: #000;
      background-color: #95d5ff;
      border-radius: 15px 2px 15px 15px;
    }
  }

  &.answer {
    align-self: flex-start;

    .chat-text {
      margin-left: 8px;
      background-color: #f4f4f5;
      border-radius: 2px 15px 15px;
    }
  }

  .chat-avatar {
    flex-shrink: 0;
    margin-top: 4px;
  }
}

.chat-text {
  max-width: 100%;
  padding: 12px 16px;
  font-size: 14px;
  line-height: 1.6;
  word-break: break-word;
  overflow-wrap: break-word;
  white-space: pre-wrap;
  box-shadow: 0 1px 2px rgb(0 0 0 / 10%);
}

.empty-tip {
  padding: 40px 0;
  font-size: 14px;
  color: #909399;
  text-align: center;
}

.chat-input {
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;

  :deep(.el-textarea__inner) {
    resize: none;
  }
}

.chat-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 12px;
}
</style>
